package com.sean.server.service;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import com.sean.util.PropertiesUtils;

@Service
public class UploadService {
	
	private Date lastDownloadTime = new Date();
	
	private Date lastUploadTime = new Date();
	
	private Date checkDownloadTime = new Date();
	
	private static String TEMP_FILE_PATH = PropertiesUtils.getString("this.temp.file");
	
	private static String CLIENT_PASSWORD = PropertiesUtils.getString("client.password");
	
    public void save(InputStream in) throws IOException {  
		FileOutputStream file = new FileOutputStream(TEMP_FILE_PATH);
		IOUtils.copy(in, file);
		lastUploadTime = new Date();
    }
    
    public void download(OutputStream out) throws IOException {  
    	FileInputStream inFile = new FileInputStream(TEMP_FILE_PATH);
		IOUtils.copy(inFile, out);
		lastDownloadTime = new Date();
    }
	
    public String isUpload() throws IOException {  
		if((checkDownloadTime.getTime() + 1000*5) > (new Date()).getTime()) {
			return "YES";
		}
        return "NO";
    }
    
    public String isDownload() throws IOException {
    	checkDownloadTime = new Date();
		if(lastUploadTime.getTime() > lastDownloadTime.getTime()) {
			return "YES";
		}
        return "NO";  
    }

	public boolean auth(String p) {
		if(CLIENT_PASSWORD.equals(p)) {
			return true;
		}
		return false;
	} 
}
